//
//  BRBindAccountVC.m
//  Kexu
//
//  Created by IOS on 2023/7/21.
//

#import "BRBindAccountVC.h"
#import "BRAreaViewController.h"

@interface BRBindAccountVC ()<QMUITextFieldDelegate>
{
    QMUITextField *_phoneTF;
    QMUITextField *_emailTF;
    QMUITextField *_OtpTF;
    QMUIButton *_areaBtn;
    QMUIButton *_otpBtn;
    QMUIButton *_nextBtn;
}


@end

@implementation BRBindAccountVC

- (void)viewDidLoad {
    [super viewDidLoad];
    // Do any additional setup after loading the view.
    [self setUI];
}

- (void)viewWillAppear:(BOOL)animated {
    [super viewWillAppear:animated];
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(notificationDoit) name:APPTIMEINFORMATION object:nil];
}

- (void)viewDidDisappear:(BOOL)animated {
    [super viewDidDisappear:animated];
    
    [self.view endEditing:YES];
}

- (void)dealloc {
    
    [[NSNotificationCenter defaultCenter] removeObserver:self];
}

#pragma mark - Net --
- (void)iGetCode {
    
    [BRHud showHud];
    
    NSString *codeStr = [_areaBtn.titleLabel.text substringFromIndex:1];
    
    NSMutableDictionary *dic = [NSMutableDictionary dictionary];
   
    
    if (self.isEmail) {
        dic[@"email"] = _emailTF.text;
        dic[@"scene"] = @3;
    }else {
        dic[@"code"] = [self->_areaBtn.titleLabel.text substringFromIndex:1];
        dic[@"phone"] = _phoneTF.text;
        dic[@"scene"] = @2;
    }
    
    [[BRRequestManager shared] GET:[BRAPI verificationCode] params:dic succeed:^(NSDictionary * _Nonnull dataDict, NSInteger respCode) {
        
        if (!self.isEmail) {
            [BrezzeTimeManage share].loginCode = codeStr;
            [BrezzeTimeManage share].loginPhone = self->_phoneTF.text;
        }else {
            [BrezzeTimeManage share].loginEmail = self->_emailTF.text;
        }
        [BrezzeTimeManage addObjectIndateDic:self.otpTimeKey];
        [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(notificationDoit) name:APPTIMEINFORMATION object:nil];
        [BRHud hidden];
        
    } failed:^(NSInteger code, NSString * _Nonnull errMsg) {
        [BRHud hidden];
        if (code == 21012) {
            if (errMsg.length > 0) {
                [BRHud showTips:errMsg];
            }
           
        }
    }];
}

- (void)cheackAccount {
    
    [BRHud showInView:self.view];
    NSMutableDictionary *dic = [NSMutableDictionary dictionary];
    dic[@"msgCode"] = _OtpTF.text;
    if (!self.isEmail) {
        dic[@"code"] = [_areaBtn.titleLabel.text substringFromIndex:1];
        dic[@"phone"] = _phoneTF.text;
    }else {
        dic[@"email"] = _emailTF.text;
    }
//    [[BRRequestManager shared] GET:[BRAPI checkCurrAccount] params:dic succeed:^(NSDictionary * _Nonnull dataDict, NSInteger respCode) {
//
//        [BRHud hiddenInView:self.view];
//        self.type = 1;
//
//
//    } failed:^(NSInteger code, NSString * _Nonnull errMsg) {
//        [BRHud hiddenInView:self.view];
//    }];
}

- (void)bindAccount {
    
    [BRHud showInView:self.view];
   
    NSMutableDictionary *dic = [NSMutableDictionary dictionary];
    dic[@"msgCode"] = _OtpTF.text;
    if (!self.isEmail) {
        dic[@"code"] = [_areaBtn.titleLabel.text substringFromIndex:1];
        dic[@"phone"] = _phoneTF.text;
    }else {
        dic[@"email"] = _emailTF.text;
    }
    [self changeInfo:dic succ:^{
//        if (!self.isEmail) {
//            USERManager.userModel.code = [self->_areaBtn.titleLabel.text substringFromIndex:1].integerValue;
//            USERManager.userModel.phone = self->_phoneTF.text;
//        }else {
//            USERManager.userModel.email = self->_emailTF.text;
//        }
        
        [BRHud hiddenInView:self.view];
        [BRHud showAutoSuccInView:self.view];
        
        dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(1.5 * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
            [self pop];
        });
        
    } faile:^{
        [BRHud hiddenInView:self.view];
    }];
    
}

- (void)changeInfo:(NSDictionary *)infoDic succ:(void(^)(void))succ faile:(void(^)(void))faile {
    
    [BRHud showHud];
    [[BRRequestManager shared] PUT:[BRAPI editUserInfo] params:infoDic succeed:^(NSDictionary * _Nonnull dataDict, NSInteger respCode) {
        
        
        [BRUserManager requestUserInfo:^{
            
        } faile:^{
            
        }];
        
        [BRHud hidden];
        if (succ) {
            succ();
        }
        
    } failed:^(NSInteger code, NSString * _Nonnull errMsg) {
        [BRHud hidden];
        if (faile) {
            faile();
        }
    }];
}

#pragma mark - 监听
- (void)notificationDoit {
    
    if ([BrezzeTimeManage getimeIntervalBy:self.otpTimeKey wirhMax:kTimeMax] > 0) {
        dispatch_async(dispatch_get_main_queue(), ^{
            [self startTimeStr];
        });
    }else{
        
        dispatch_async(dispatch_get_main_queue(), ^{
            
            [self removeTime];
        });
    }
}

- (void)startTimeStr {
    _otpBtn.enabled = NO;
    NSInteger num = [BrezzeTimeManage getimeIntervalBy:self.otpTimeKey wirhMax:kTimeMax];
    NSString *str2 = [NSString stringWithFormat:@"%02lds",(long)num];
    [self->_otpBtn setTitle:str2 forState:(UIControlStateNormal)];
}

- (void)removeTime {
    
    self->_otpBtn.enabled = YES;
    
    [self->_otpBtn setTitle:Localized(@"login_get") forState:(UIControlStateNormal)];
    [BrezzeTimeManage removeObjectKey:self.otpTimeKey];
}

#pragma mark - Action --
- (void)nextTap:(QMUIButton *)btn {
    
    if (self.isEmail) {
        
        if (_emailTF.text.length == 0) {
            [BRHud show:Localized(@"toast_requiredEmail") inView:self.view];
            return;
        }
        if (![BRTools checkEmail:_emailTF.text]) {
            
            [BRHud show:Localized(@"toast_validEmail") inView:self.view];
            
            return;
        }
        
    }else {

        if (_phoneTF.text.length == 0) {
            
            [BRHud show:Localized(@"toast_requiredPhone") inView:self.view];
            return;
        }
        if (![BRTools checkPhone:_phoneTF.text]) {
            
            [BRHud show:Localized(@"toast_validPhone") inView:self.view];
            
            return;
        }
    }
    
    if (_OtpTF.text.length != 4) {
        
        NSString *otpError = _OtpTF.text.length == 0 ? Localized(@"toast_requiredCode") : Localized(@"toast_validCode");
        
        [BRHud show:otpError inView:self.view];
        
        return;
    }
        
    
    [self bindAccount];
}

- (void)getAreaNum {
    
    [self.view endEditing:YES];
    BRAreaViewController *vc = [[BRAreaViewController alloc] init];
    vc.isLogin = YES;
    [self.navigationController pushViewController:vc animated:YES];
    vc.selectCodeBlock = ^(NSInteger code) {
        [self->_areaBtn setTitle:[NSString stringWithFormat:@"+%ld",code] forState:UIControlStateNormal];
    };
}

- (void)sendOtpClick:(QMUIButton *)btn {
    
    
    
    if (self.isEmail) {
        
        if (_emailTF.text.length == 0) {
            [BRHud show:Localized(@"toast_requiredEmail") inView:self.view];
            return;
        }
        if (![BRTools checkEmail:_emailTF.text]) {
            
            [BRHud show:Localized(@"toast_validEmail") inView:self.view];
            
            return;
        }
        
    }else {
        if (_phoneTF.text.length == 0) {
            
            [BRHud show:Localized(@"toast_requiredPhone") inView:self.view];
            return;
        }
        if (![BRTools checkPhone:_phoneTF.text]) {
            
            [BRHud show:Localized(@"toast_validPhone") inView:self.view];
            
            return;
        }
    }
    
    
    [self.view endEditing:YES];
    [self iGetCode];
    
}
     
- (NSString *)otpTimeKey {
    return self.isEmail ? @"BRMChangeEmail" : @"BRMChangePhoneNum";
}

#pragma mark - TextField Delegate --
- (void)textFieldDidEndEditing:(UITextField *)textField reason:(UITextFieldDidEndEditingReason)reason {
    
    NSLog(@"textFieldDidEndEditing = %@",textField.text);
}

- (BOOL)textFieldShouldEndEditing:(UITextField *)textField {
    
    NSLog(@"textFieldShouldEndEditing = %@",textField.text);
    
    return YES;
}

- (BOOL)textFieldShouldBeginEditing:(UITextField *)textField {
    NSLog(@"textFieldShouldBeginEditing = %@",textField.text);
    
    return YES;
}

- (void)textFieldDidChangeSelection:(UITextField *)textField {
    if (textField == _OtpTF) {
        if (textField.text.length >= 4) {
            [textField resignFirstResponder];
        }
    }
}

- (BOOL)textField:(UITextField *)textField shouldChangeCharactersInRange:(NSRange)range replacementString:(NSString *)string {
    
    if (textField == _emailTF) {
        return [BRTools canInputText:string hasEmail:YES];
    }
    return YES;
}

#pragma mark - UI --
- (void)setUI {
    NSString *title = Localized(@"profile_addPhone");
//    NSString *text = Localized(@"profile_verifyPhoneNum");
    if (self.isEmail) {
        title = Localized(@"profile_addEmail");
//        text = Localized(@"profile_verifyEmail");
    }
    [self br_createTop:title];
    
    //UIColorMake(60, 144, 255)
//    self.view.backgroundColor = UIColorWhite;
    UIColor *placeholderColor = kColorTitle888;
    UIColor *textInputC = kColorTitle;
    UIColor *bgColor = kColorBGEC;

    QMUITextField *phoneTf = [[QMUITextField alloc] init];
    phoneTf.clearButtonMode = UITextFieldViewModeWhileEditing;
    phoneTf.clearButtonPositionAdjustment = UIOffsetMake(-20, 0);
    phoneTf.textInsets = UIEdgeInsetsMake(0, 110, 0, 20);
    phoneTf.placeholderColor = placeholderColor;
    phoneTf.minimumFontSize = 10;
    phoneTf.adjustsFontSizeToFitWidth = YES;
    phoneTf.textColor =  textInputC;
    phoneTf.tintColor = kColorMain;
    phoneTf.font  = [UIFont fontS:14];
    phoneTf.placeholder = Localized(@"profile_enterPhoneNum");
    [self.view addSubview:phoneTf];
    phoneTf.layer.cornerRadius = 14;
    phoneTf.backgroundColor = bgColor;
    [phoneTf mas_makeConstraints:^(MASConstraintMaker *make) {
        make.width.mas_equalTo(kScreenWidth - 56);
        make.height.mas_equalTo(56);
        make.centerX.equalTo(self.view);
        make.top.offset(28 + kSafeAreaTopHeight);
    }];
    phoneTf.maximumTextLength = 15;
    phoneTf.keyboardType = UIKeyboardTypePhonePad;
//    phoneTf.text = USERManager.userModel.phone;
    
    QMUITextField *emailTf = [[QMUITextField alloc] init];
    emailTf.clearButtonMode = UITextFieldViewModeWhileEditing;
    emailTf.clearButtonPositionAdjustment = UIOffsetMake(-20, 0);
    emailTf.textInsets = UIEdgeInsetsMake(0, 40, 0, 20);
    emailTf.placeholderColor = placeholderColor;
    emailTf.minimumFontSize = 10;
    emailTf.adjustsFontSizeToFitWidth = YES;
    emailTf.textColor =  textInputC;
    emailTf.tintColor = kColorMain;
    emailTf.font  = [UIFont fontS:14];
    emailTf.placeholder = Localized(@"profile_enterEmail");
    [self.view addSubview:emailTf];
    emailTf.layer.cornerRadius = 14;
    emailTf.backgroundColor = bgColor;
    [emailTf mas_makeConstraints:^(MASConstraintMaker *make) {
        make.width.mas_equalTo(kScreenWidth - 56);
        make.height.mas_equalTo(56);
        make.centerX.equalTo(self.view);
        make.top.offset(28 + kSafeAreaTopHeight);
    }];
    emailTf.maximumTextLength = 150;
    emailTf.keyboardType = UIKeyboardTypeEmailAddress;
//    emailTf.text = USERManager.userModel.email;
    
//    NSString *codeStr = [NSString stringWithFormat:@"+%ld",USERManager.userModel.code];

    QMUIButton *areaBtn = [[QMUIButton alloc] qmui_initWithImage:UIImageMake(@"login_ic_more") title:kAddCountryCode];
    areaBtn.imagePosition = QMUIButtonImagePositionRight;
    areaBtn.imageEdgeInsets = UIEdgeInsetsMake(0, 4, 0, 0);
//    QMUIButton *areaBtn = [[QMUIButton alloc] init];
//    [areaBtn setTitle:@"+35" forState:UIControlStateNormal];
    [areaBtn setTitleColor:textInputC forState:UIControlStateNormal];
    areaBtn.titleLabel.font = [UIFont br_fontM:16];
    [phoneTf addSubview:areaBtn];
    [areaBtn mas_makeConstraints:^(MASConstraintMaker *make) {
        make.centerY.equalTo(phoneTf);
        make.left.equalTo(phoneTf).offset(8);
        make.height.mas_equalTo(44);
        make.width.mas_equalTo(88);
    }];
    [areaBtn addTarget:self action:@selector(getAreaNum) forControlEvents:UIControlEventTouchUpInside];
    
    QMUITextField *otpTf = [[QMUITextField alloc] init];
    otpTf.clearButtonMode = UITextFieldViewModeWhileEditing;
    otpTf.clearButtonPositionAdjustment = UIOffsetMake(-100, 0);
    otpTf.textInsets = UIEdgeInsetsMake(0, 40, 0, 110);
    otpTf.placeholder = Localized(@"login_verificationCode");
    otpTf.placeholderColor = placeholderColor;
    otpTf.font = [UIFont fontM:14];
    [self.view addSubview:otpTf];
    otpTf.layer.cornerRadius = 14;
    otpTf.textColor =  textInputC;
    otpTf.tintColor = kColorMain;
    otpTf.backgroundColor = bgColor;
    [otpTf mas_makeConstraints:^(MASConstraintMaker *make) {
        make.width.mas_equalTo(kScreenWidth - 56);
        make.height.mas_equalTo(56);
        make.centerX.equalTo(self.view);
        make.top.equalTo(phoneTf.mas_bottom).offset(20);
    }];
    otpTf.maximumTextLength = 4;
    otpTf.keyboardType = UIKeyboardTypePhonePad;
    
    QMUIButton *otpBtn = [[QMUIButton alloc] init];
    [otpBtn setTitle:Localized(@"login_get") forState:UIControlStateNormal];
    [otpBtn setTitleColor:UIColorWhite forState:UIControlStateNormal];
    [otpBtn setTitleColor:UIColorWhite forState:UIControlStateDisabled];
    [otpBtn setBackgroundColor:kColorMain];
    otpBtn.titleLabel.font = [UIFont fontS:12];
    otpBtn.layer.cornerRadius = 6;
    otpBtn.layer.masksToBounds = YES;
    [otpTf addSubview:otpBtn];
    [otpBtn mas_makeConstraints:^(MASConstraintMaker *make) {
        make.centerY.equalTo(otpTf);
        make.right.equalTo(otpTf).offset(-8);
        make.height.mas_equalTo(40);
        make.width.mas_equalTo(88);
    }];
    [otpBtn addTarget:self action:@selector(sendOtpClick:) forControlEvents:UIControlEventTouchUpInside];
    
    phoneTf.hidden = self.isEmail;
    emailTf.hidden = !self.isEmail;
    
    _phoneTF = phoneTf;
    _emailTF = emailTf;
    _OtpTF = otpTf;
    _emailTF.delegate = self;
    _phoneTF.delegate = self;
    _OtpTF.delegate = self;
    _otpBtn = otpBtn;
    _areaBtn = areaBtn;
//    if ([BrezzeTimeManage share].loginCode.length != 0) {
//        [areaBtn setTitle:[NSString stringWithFormat:@"+%@",[BrezzeTimeManage share].loginCode] forState:UIControlStateNormal];
//    }
//    if (USERManager.userModel.phone.length != 0) {
//        phoneTf.text = USERManager.userModel.phone;
//        [areaBtn setTitle:[NSString stringWithFormat:@"+%@",[BrezzeTimeManage share].loginCode] forState:UIControlStateNormal];
//    }
//    if (USERManager.userModel.email.length != 0) {
//        emailTf.text = USERManager.userModel.email;
//    }
    
    QMUIButton *nextBtn = [BRToolsView br_btnBGImg:Localized(@"profile_link")];
    [self.view addSubview:nextBtn];
    [nextBtn mas_makeConstraints:^(MASConstraintMaker *make) {
        make.centerX.equalTo(self.view);
        make.left.offset(16);
        make.right.offset(-16);
        make.height.mas_equalTo(52);
        make.bottom.offset(- (15 + kSafeAreaBottomHeight));
    }];
    
    [nextBtn addTarget:self action:@selector(nextTap:) forControlEvents:UIControlEventTouchUpInside];
    _nextBtn = nextBtn;
    
//    [self br_changTopY];
}
/*
#pragma mark - Navigation

// In a storyboard-based application, you will often want to do a little preparation before navigation
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
    // Get the new view controller using [segue destinationViewController].
    // Pass the selected object to the new view controller.
}
*/

@end
